﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using UMC.Web.UI;
using UMC.Web;
using UMC.Security;
using UMC.Wiki.Entities;
using System.Linq;
namespace UMC.Wiki.Activities
{

    class SubjectProjectUIActivity : WebActivity
    {
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var ProjectId = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("Id", g =>
            {
                this.Prompt("请输入项目");

                return this.DialogValue("Project");
            })) ?? 0;// ?? Guid.Empty;
            var project = DataFactory.Instance().Project(ProjectId);

            var Model = this.AsyncDialog("Model", ml =>
             {
                 if (project == null)
                 {
                     return this.DialogValue("News");
                 }
                 var form = (request.SendValues ?? new UMC.Web.WebMeta()).GetDictionary();
                 if (form?.ContainsKey("start") != true)
                 {

                     if (request.Url.Query.Contains("_v=Sub"))
                     {
                         this.Context.Send("Subject.Path", new WebMeta().Put("Path", project.Code), true);
                     }
                 }
                 var webr = UMC.Web.WebResource.Instance();
                 UISection ui = null;
                 UISection ui2 = null;

                 var selectIndex = UMC.Data.Utility.IntParse(request.SendValues?["selectIndex"], 0);
                 var items = new List<WebMeta>();//
                 items.Add(new UMC.Web.WebMeta().Put("text", "文档目录", "search", "Subs", "Key", "List"));
                 items.Add(new UMC.Web.WebMeta().Put("text", "团队成员", "search", "Member", "Key", "List"));
                 items.Add(new UMC.Web.WebMeta().Put("text", "项目动态", "search", "Dynamic", "Key", "List"));

                 var Keyword = (form["Keyword"] as string ?? String.Empty);
                 if (String.IsNullOrEmpty(Keyword) && selectIndex > -1)
                 {
                     Keyword = items[selectIndex]["search"];
                 }

                 int start = UMC.Data.Utility.IntParse(form["start"] as string, 0);
                 var nextKey = request.SendValues?["NextKey"] ?? "Header";
                 if (start == 0 && String.Equals(nextKey, "Header"))
                 {
                     var logoUrl = webr.ImageResolve(request.Url, project.Id.Value, "1", 4);
                     var Discount = new UIHeader.Portrait(logoUrl);
                     Discount.Value(project.Caption);
                     Discount.Time(project.Description);

                     var color = 0x63b359;
                     Discount.Gradient(color, color);
                     var header = new UIHeader();
                     var title = UITitle.Create();

                     title.Title = "项目介绍";
                     title.Style.BgColor(color);
                     title.Style.Color(0xfff);

                     header.AddPortrait(Discount, new UIStyle().Name("image-radius", "10"));

                     ui = UISection.Create(header, title);
                     bool isIsAttention;

                     UIIconNameDesc uIIcon = new UIIconNameDesc();//
                     uIIcon.Put("icon", '\uF0c0').Put("color", "#40c9c6").Put("name", "团队规模").Put("desc", project.MemberTotal + "人");
                     var idReader = DataFactory.Instance().ProjectReader(this.Context.Token.UserId.Value, project.Id.Value) != null;
                     if (idReader)
                     {
                         uIIcon.Button("已订阅", null, 0x25b864);
                     }
                     else
                     {
                         uIIcon.Button(SubjectAttentionActivity.Attention(this.Context, project.Id.Value, out isIsAttention), Web.UIClick.Click(new Web.UIClick() { Model = request.Model, Command = "ProjectAtten" }.Send("Id", project.Id.ToString())), isIsAttention ? 0x36a3f7 : 0xe67979);

                     }
                     ui.Add(uIIcon);

                     uIIcon = new UIIconNameDesc(new UIIconNameDesc.Item('\uF02d', "文章数量", project.SubjectTotal + "篇").Color(0x36a3f7), new UIIconNameDesc.Item('\uf06e', "浏览总数", project.ViewTotal + "次").Color(0x34bfa3));
                     ui.Add(uIIcon);
                     ui2 = ui.NewSection();


                 }
                 else
                 {
                     ui2 = ui = UISection.Create();

                 }
                 if (start == 0 && String.Equals(nextKey, "Self") == false)
                 {
                     if (selectIndex > 0)
                     {

                         ui2.Add(UICell.Create("TabFixed", new UMC.Web.WebMeta().Put("items", items).Put("selectIndex", selectIndex)));
                     }
                     else
                     {
                         ui2.Add(UICell.Create("TabFixed", new UMC.Web.WebMeta().Put("items", items))); ;

                     }
                 }
                 ui2.Key = "List";
                 int limit = UMC.Data.Utility.IntParse(form["limit"] as string, 25);
                 switch (Keyword)
                 {
                     default:
                     case "Subs":
                         {

                             var Type = this.AsyncDialog("Type", "Items");

                             var itemId = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("CId", project.Id.ToString()));


                             switch (Type)
                             {
                                 case "Items":
                                     {

                                         UMC.Data.Utility.Each(DataFactory.Instance().ProjectItem(project), dr =>
                                          {
                                              if ((dr.Hide ?? false) == false)
                                              {
                                                  ui2.AddCell('\uf022', dr.Caption, String.Format("{0}篇", dr.SubjectTotal ?? 0)
                                                   , UIClick.Query("List", new WebMeta().Put("CId", dr.Id).Put("Type", "Portfolio")));
                                              }
                                          });
                                     }
                                     break;
                                 case "Portfolio":
                                     {

                                         var item = DataFactory.Instance().ProjectItem(itemId.Value);// UMC.Data.Utility.CMS.ObjectEntity<ProjectItem>().Where.And().In(new ProjectItem { Id = itemId }).Entities.Single();
                                         var navData = new WebMeta().Put("item", item.Caption).Put("Icon", '\uf022');

                                         navData.Put("nav", "目录");
                                         navData.Put("split", '\uf105');
                                         var cell = UICell.Create("UI", navData);
                                         cell.Style.Name("nav").Click(UIClick.Query("List", new WebMeta().Put("CId", item.project_id).Put("Type", "Items"))).Color(0x36a3f7);
                                         cell.Style.Name("item").Color(0x999);
                                         cell.Formats.Put("text", "{nav} {split} {item}");
                                         cell.Style.Name("split").Font("wdk");

                                         ui2.Add(cell);

                                         var subs = DataFactory.Instance().Search(new Subject { project_id = item.project_id, project_item_id = item.Id, Status = 1 }, 0, out var __, 500);

                                         UMC.Data.Utility.Each(DataFactory.Instance().Portfolio(item).OrderBy(o => o.Sequence ?? 0), dr =>
                                         {

                                             var sbs = subs.Where(r => r.portfolio_id == dr.Id).OrderBy(o => o.Seq ?? 0);
                                             if (subs.Length > 0)
                                             {
                                                 var ui3 = ui2.NewSection();
                                                 ui3.Header.Put("text", dr.Caption);
                                                 SubjectUIActivity.Search(ui3, sbs.ToArray(), request.Model, "UIData", false, request.IsApp, request.Url);


                                             }
                                         });



                                     }
                                     break;
                                 case "Subs":
                                     {
                                         var ui3 = ui2;
                                         if (start == 0)
                                         {
                                             var portfolio = DataFactory.Instance().Portfolio(itemId.Value);

                                             var item = DataFactory.Instance().ProjectItem(portfolio.project_item_id.Value);

                                             var navData = new WebMeta().Put("item", item.Caption).Put("Icon", '\uf022');

                                             navData.Put("nav", "目录");
                                             navData.Put("split", '\uf105');
                                             navData.Put("port", portfolio.Caption);
                                             var cell = UICell.Create("UI", navData);
                                             cell.Style.Name("nav").Click(UIClick.Query("List", new WebMeta().Put("CId", item.project_id).Put("Type", "Items"))).Color(0x36a3f7);
                                             cell.Style.Name("item").Color(0x36a3f7).Click(UIClick.Query("List", new WebMeta().Put("CId", item.Id).Put("Type", "Portfolio")));
                                             cell.Formats.Put("text", "{nav} {split} {item} {split} {port}");

                                             cell.Style.Name("port").Color(0x999);
                                             cell.Style.Name("split").Font("wdk");
                                             ui2.Add(cell);

                                             ui3 = ui2.NewSection();

                                         }
                                         ui3.Key = "Subs";
                                         int nextIndex;
                                         SubjectUIActivity.Search(ui3, DataFactory.Instance().Search(new Subject { portfolio_id = itemId, Status = 1 }, start, out nextIndex, limit), request.Model, "UIData", false, request.IsApp, request.Url);

                                         if (ui3.Length == 0 && start == 0)
                                         {
                                             ui2.IsNext = false;
                                             ui3.Add("Desc", new UMC.Web.WebMeta().Put("desc", "尚未有发布的项目资讯").Put("icon", "\uF016")
                                                 , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"), new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));

                                         }
                                         else
                                         {
                                             ui2.IsNext = nextIndex > 0;
                                             ui2.StartIndex = nextIndex;
                                         }



                                     }
                                     break;
                             }

                         }
                         break;
                     case "Member":
                         {
                             var style = new UIStyle().AlignLeft();
                             int mlimit = limit * 4;
                             int mnextIndex;
                             var pms = DataFactory.Instance().Search(new ProjectMember
                             {
                                 project_id = project.Id
                             }, start, out mnextIndex, mlimit);

                             if (pms.Length > 0)
                             {
                                 var icons = new List<UIEventText>();
                                 var ites = new List<UIIconNameDesc.Item>();
                                 foreach (var pm in pms)
                                 {
                                     switch (pm.AuthType)
                                     {
                                         case WebAuthType.Admin:
                                         case WebAuthType.User:
                                             var text = "专栏作家";
                                             switch (pm.AuthType)
                                             {
                                                 case WebAuthType.Admin:
                                                     text = "项目主";
                                                     break;
                                                 case WebAuthType.User:
                                                     break;
                                             }
                                             ites.Add(new UIIconNameDesc.Item(webr.ImageResolve(request.Url, pm.user_id.Value, "1", "4"), pm.Alias, text)
                                                 .Click(new UIClick(request.Model, "Account", pm.user_id.ToString())));
                                             if (ites.Count % 2 == 0)
                                             {
                                                 ui2.Add(new UIIconNameDesc(ites.ToArray()));
                                                 ites.Clear();
                                             }
                                             break;
                                         default:
                                         case WebAuthType.Guest:

                                             if (ites.Count > 0)
                                             {
                                                 ui2.Add(new UIIconNameDesc(ites.ToArray()));
                                                 ites.Clear();
                                             }

                                             icons.Add(new UIEventText(pm.Alias).Src(webr.ImageResolve(request.Url, pm.user_id.Value, "1", "4")).Click(new UIClick(request.Model, "Account", pm.user_id.ToString())));

                                             if (icons.Count % 4 == 0)
                                             {
                                                 ui2.Add(new Web.UI.UIIcon().Add(icons.ToArray()));
                                                 icons.Clear();
                                             }
                                             break;
                                     }


                                 }
                                 if (ites.Count > 0)
                                 {
                                     ui2.Add(new UIIconNameDesc(ites.ToArray()));
                                     ites.Clear();
                                 }
                                 if (icons.Count > 0)
                                 {
                                     var ls = new Web.UI.UIIcon().Add(icons.ToArray());
                                     ls.Style.Copy(style);
                                     ui2.Add(ls);
                                 }

                             }
                             ui.IsNext = mnextIndex > 0;
                             ui.StartIndex = mnextIndex;
                             //  response.Redirect(ui);
                             ui.SendTo(this.Context);
                         }
                         break;
                     case "Writer":
                         {
                             var wmpms = DataFactory.Instance().ProjectMember(project.Id.Value, WebAuthType.Admin, WebAuthType.User);
                             var style = new UIStyle().AlignRight();
                             if (wmpms.Length > 0)
                             {

                                 var icons = new List<UIEventText>();
                                 foreach (var v in wmpms)
                                 {

                                     icons.Add(new UIEventText(v.Alias).Src(webr.ImageResolve(request.Url, v.user_id.Value, "1", "4")).Click(new UIClick(request.Model, "Account", v.user_id.ToString())));

                                     if (icons.Count % 4 == 0)
                                     {
                                         ui2.Add(new Web.UI.UIIcon().Add(icons.ToArray()));
                                         icons.Clear();
                                     }

                                 }
                                 if (icons.Count > 0)
                                 {
                                     var ls = new Web.UI.UIIcon().Add(icons.ToArray());
                                     ls.Style.Copy(style);
                                     ui2.Add(ls);
                                 }
                             }
                             ui.IsNext = false;
                             response.Redirect(ui);
                         }
                         break;
                     case "Dynamic":
                         {
                             int nextIndex;
                             var subs = DataFactory.Instance().Search(new ProjectDynamic
                             {
                                 project_id = project.Id
                             }, start, out nextIndex, limit);

                             foreach (var sub in subs)
                             {
                                 var data = new WebMeta().Put("alias", sub.Alias, "desc", sub.Explain).Put("time", sub.Time)
                                     .Put("name", sub.Title)
                                     .Put("src", webr.ImageResolve(request.Url, sub.user_id ?? Guid.Empty, "1", 5));
                                 var cell = UICell.Create("IconNameDesc", data);

                                 cell.Formats.Put("desc", "{alias} {time} {desc}");
                                 cell.Style.Name("name").Size(14);
                                 ui2.Add(cell);
                             }
                             if (subs.Length == 0 && start == 0)
                             {
                                 ui.IsNext = false;
                                 ui2.Add("Desc", new UMC.Web.WebMeta().Put("desc", "尚未有项目动态").Put("icon", "\uF016")
                                     , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"), new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                             }
                             else
                             {
                                 ui.IsNext = nextIndex > 0;
                                 ui.StartIndex = nextIndex;
                             }
                         }
                         break;


                 }

                 ui.SendTo(this.Context);

                 //  response.Redirect(ui);
                 return this.DialogValue("none");
             });
            var user = this.Context.Token.Identity();
            if (user.IsAuthenticated == false)
            {
                this.Prompt("请登录", false);
                this.Context.Send("Login", true);
                // response.Redirect("Account", "Login");
            }
            if (project != null)
            {
                var member = DataFactory.Instance().ProjectMember(project.Id.Value, user.Id.Value);

                if (member != null)
                {
                    switch (member.AuthType)
                    {
                        case WebAuthType.Admin:
                            break;
                        default:
                            this.Prompt("您未有编辑此项目的权限");
                            break;
                    }

                }
                else
                {
                    this.Prompt("您未有编辑此项目的权限");
                }

                var Caption = this.AsyncDialog("Settings", d =>
                {

                    var fmdg = new Web.UIFormDialog();
                    fmdg.Title = "编辑项目";
                    switch (Model)
                    {
                        case "Icon":
                            var icon = this.AsyncDialog(d, "System", "Image", new WebMeta().Put("id", ProjectId).Put("index", 1));
                            return this.DialogValue(new WebMeta("Icon", icon));
                        case "Caption":
                            fmdg.Title = "项目名称";
                            fmdg.AddText("项目名称", "Caption", project.Caption);
                            break;
                        case "Description":
                            fmdg.Title = "项目简介";
                            fmdg.AddText("搜索关健字", "Keywords", project.Keywords).PlaceHolder("搜索引擎SEO优化").NotRequired();
                            fmdg.AddText("简短描述", "Description", project.Description).PlaceHolder("搜索引擎SEO优化");

                            break;
                        case "Code":
                            fmdg.Title = "项目简码";
                            fmdg.AddText("项目简码", "Code", project.Code).PlaceHolder("短小易记有助于访问和传播").Put("tip", "");
                            break;
                    }
                    fmdg.Submit("确认", "Subject.Project");
                    return fmdg;

                });
                var team = new Project();

                UMC.Data.Reflection.SetProperty(team, Caption.GetDictionary());
                if (String.IsNullOrEmpty(team.Code) == false)
                {
                    //team.Code = team.Code.ToLower();
                    if (team.Code.Length < 3)
                    {
                        this.Prompt("项目简码必须大于3个字符");
                    }
                    if (System.Text.RegularExpressions.Regex.IsMatch(team.Code, "^\\d+$") == true)
                    {
                        this.Prompt("项目简码不能全是数字");

                    }
                    if (System.Text.RegularExpressions.Regex.IsMatch(team.Code, "^[0-9a-z]+$") == false)
                    {
                        this.Prompt("项目简码只能是小写字符和数字");
                    }
                    if (String.Equals(team.Code, project.Code, StringComparison.CurrentCulture) == false)
                    {

                        if (DataFactory.Instance().Project(team.Code) != null)
                        {
                            this.Prompt("存在相同的简码");
                        }

                    }
                }

                team.ModifiedTime = DateTime.Now;

                team.Id = project.Id;
                DataFactory.Instance().Put(team);

                this.Prompt("修改成功", false);
                this.Context.Send(new UMC.Web.WebMeta().Put("type", "Subject.Project").Put("id", project.Id).Put("text", team.Caption ?? project.Caption).Put("code", team.Code ?? project.Code), true);


            }

        }
    }
}